<template>
  <Loader :loading="loading">
    <view class="flex-col group">
      <view class="flex-col section_4">
        <view class="flex-row items-center">
          <image class="image_7" src="/static/icon/notice_pink.svg" />
          <text class="font_2 text_3 ml-5">说明：</text>
        </view>
        <text class="font text_4 mt-7">请完成以下两个评估问卷，帮助我们更好地了解您的健康状况：</text>
      </view>

      <progress
        show-info
        font-size="12"
        class="progress mt-12"
        :percent="progressPercent"
        activeColor="#F26A77"
        backgroundColor="#FFFFFF"
        border-radius="8"
        active
        active-mode="forwards"
        duration="20"
      />

      <view class="flex-col items-center mt-12">
        <scroll-view class="flex-col assesscard-container" scroll-y enable-flex>
          <assess-card
            class="section_7 mt-10"
            v-for="item in healthtestItems"
            :key="item.id"
            :item="item"
            :done="doneList[item.id]"
            @clearAssess="bindClearAssess"
            @finishAssess="bindFinishAssess"
          ></assess-card>
        </scroll-view>

        <button
          class="mt-12"
          :class="allDone ? 'button-done' : 'button-undone'"
          hover-class="button-hover"
          :disabled="!allDone"
          @click="submit"
        >
          {{ allDone ? "提交" : "未完成" }}
        </button>
      </view>
    </view>
  </Loader>
</template>

<script>
import { saveResults, generateTags, getCompressor, getHealthtestConfig } from "../../util/questionnaire/index.js";
import { AssessCard } from "../../components/Questionnare/AssessCard/AssessCard.vue";
import Loader from "@/components/Loader/Loader.vue";

export default {
  components: {
    AssessCard,
    Loader,
  },
  data() {
    const healthtestConfig = getHealthtestConfig();
    return {
      loading: false,
      healthtestDetails: healthtestConfig.detail,
      results: {},
      resultDetails: {}
    };
  },
  computed: {
    healthtestItems() {
      return this.healthtestDetails || [];
    },
    doneList() {
      const doneList = {};
      for (const item of this.healthtestItems) {
        doneList[item.id] = !!this.results[item.id];
      }
      return doneList;
    },
    allDone() {
      return this.healthtestItems.every(item => this.doneList[item.id]);
    },
    progressPercent() {
      if (!this.healthtestItems.length) return 0;
      const doneCount = Object.values(this.doneList).filter(done => done).length;
      return Math.round((doneCount / this.healthtestItems.length) * 100);
    }
  },
  methods: {
    bindFinishAssess(res) {
      this.results[res.id] = res.result;
      
      if (res.details) {
        this.resultDetails[res.id] = res.details;
        this.$storage.set('healthtest_details', this.resultDetails);
      }
      
      this.$storage.set('healthtest_results', this.results);
      console.log("all results: ", this.results);
    },
    
    bindClearAssess(res) {
      // 清除问卷结果
      delete this.results[res.id];
      delete this.resultDetails[res.id];
      
      // 更新本地存储
      this.$storage.set('healthtest_results', this.results);
      this.$storage.set('healthtest_details', this.resultDetails);
    },
    
    submit() {
      // 合并所有details
      const mergedDetails = {};
      Object.values(this.resultDetails).forEach(details => {
        Object.assign(mergedDetails, details);
      });

      console.log("=== Healthtest Submit Debug ===");
      console.log("this.results: ", this.results);
      console.log("this.resultDetails: ", this.resultDetails);
      
      const tags = generateTags('healthtest', this.results);
      const compressor = getCompressor('healthtest');
      const compressed = compressor.compress(this.results);
      
      console.log("tags: ", tags);
      console.log("compressed: ", compressed);
      console.log("mergedDetails: ", mergedDetails);
      
      // 保存到后端
      saveResults({
        type: 'healthtest',
        result: compressed,
        details: mergedDetails,
        tags: tags,
        success: () => {
          uni.showToast({ title: "保存成功", icon: "success" });
          uni.navigateBack();
        },
        fail: (err) => {
          uni.showToast({ 
            title: "保存失败,请重试", 
            icon: "none" 
          });
        }
      });
    },
    
    loadConfig() {
      const savedResults = this.$storage.get('healthtest_results');
      const savedDetails = this.$storage.get('healthtest_details');
      if (savedResults) this.results = savedResults;
      if (savedDetails) this.resultDetails = savedDetails;
    }
  },
  mounted() {
    this.loadConfig();
  }
};
</script>

<style scoped>
.group {
  padding: 24rpx 35rpx 0;
}

.section_4 {
  padding: 16rpx 24rpx 15.86rpx;
  background-color: #ffffff;
  border-radius: 24rpx;
}

.image_7 {
  width: 48rpx;
  height: 48rpx;
}

.font_2 {
  font-size: 32rpx;
  line-height: 30.84rpx;
  font-weight: 700;
  color: #000000;
}

.text_3 {
  font-size: 30rpx;
  line-height: 29.44rpx;
}

.text_4 {
  line-height: 38rpx;
}

.assesscard-container {
  border-radius: 24rpx;
  overflow: hidden;
  border-top: solid 2rpx #e4e4e4;
  border-bottom: solid 2rpx #e4e4e4;
  max-height: 1000rpx;
}

.section_7 {
  margin-right: 4rpx;
}

.section_7:first-child {
  margin-top: 0;
}

.button-undone {
  width: 680rpx;
  border-radius: 24rpx;
  background-color: #979797 !important;
  color: #ffffff !important;
}

.button-done {
  width: 680rpx;
  border-radius: 24rpx;
  background-color: #f26a77;
  color: #ffffff;
}

.button-hover {
  background-color: #e56571;
}
</style>

<style>
page {
  background-color: #f5f5f5;
}
</style>